let uid = localStorage.getItem("uid");//loadCartList();需要用到
console.log(uid);
let cartObjArray = null; //购物车列表状态，刚开始假设为空的
loadCartList();
//1-查询用户购物车中的商品
async function loadCartList() {
  let { data } = await axios.get(cartListAPI, { params: { id: uid } });
  // console.log(data);
  // console.log(data.data);
  cartObjArray = data.data;
  // let allSelIpt = document.querySelector("#all-sel");
  updateUl();//加载购物车商品
}
// console.log(cartObjArray);//这是空的
//2-获取购物车商品列表  放到ul里
function updateUl() {
  // console.log(cartObjArray);//这不是空的，因为在loadCartList();里面调用了，里面的cartObjArray被赋值了
  let cartLiArray = cartObjArray.map(
    (pObj) => `
    <div class="item-box">
    <div class="col-check"><input type="checkbox" class="single-sel" ${pObj.checked ? 'checked' : ''}></div>
    <div class="col-img"><img src="${pObj.pimg}"></div>
    <div class="col-name">${pObj.pname}</div>
    <div class="col-price">${parseInt(pObj.pprice)}元</div>
    <div class="col-num">
    <div class="list-num">
        <input type="button" class="sub-btn" data-pid="${pObj.pid}" value="-">
        <input type="text" class="num-ipt" data-pid="${pObj.pid}" value="${pObj.pnum}">
        <input type="button" class="add-btn" data-pid="${pObj.pid}" value="+">
    </div>
    </div>
    <div class="col-total" style="color: #ff6700">${pObj.pnum * pObj.pprice}元</div>
    <div class="col-action"><a href="#" class="del-btn" data-pid="${pObj.pid}">x</a></div>
    </div>
    `
  );
  let list = document.querySelector(".list-body");//获取ul
  list.innerHTML = cartLiArray.join("");//把数组通过join方法用空字符串连接给到ul

  //获取按钮元素
  let subBtns = document.querySelectorAll(".sub-btn");//减号按钮
  let numIpts = document.querySelectorAll(".num-ipt");//商品数量框
  let addBtns = document.querySelectorAll(".add-btn");//加号按钮
  let lelBtns = document.querySelectorAll(".del-btn");//删除按钮
  let pCounts = document.querySelectorAll(".col-total");//单个商品的价格

  //2-1加号添加事件
  addBtns.forEach((btn, i) => {
    btn.onclick = async () => {
      let pid = btn.getAttribute("data-pid");//获取按钮上的自定义属性值
      let pObj = cartObjArray.find((v) => v.pid === pid);//利用find方法找到自己所在行的商品******
      // console.log(pObj);
      pObj.pnum++;//数量加一
      // console.log(pObj.pnum);
      // console.log(pid, uid);
      //发送请求，把已经改变的商品数量给到接口
      let { data } = await axios.get(cartUpdateAPI, {
        params: { pnum: pObj.pnum, pid, uid },
      });
      calCountPrice();//计算总价
      updateUl();//重新加载商品列表
    };
  });

  //2-2减号添加事件 原理和上面一样
  subBtns.forEach((btn, i) => {
    btn.onclick = async () => {
      let pid = btn.getAttribute("data-pid");
      let pObj = cartObjArray.find((v) => v.pid === pid);
      if (pObj.pnum == 1) {//到1就不然点了
        return;
      }
      pObj.pnum--;
      // console.log(pObj.pnum);
      // console.log(pid, uid);
      let { data } = await axios.get(cartUpdateAPI, {
        params: { pnum: pObj.pnum, pid, uid },
      });
      calCountPrice();//计算总价
      updateUl();//重新加载列表
    };
  });

  //2-3给商品数量 输入框 添加事件
  numIpts.forEach((ipt, i) => {
    let num = ipt.value;
    // console.log(num);//num是当前每个商品的商品数量
    ipt.onchange = () => {
      console.log(ipt);
      let value = ipt.value;
      let pid = ipt.getAttribute("data-pid");
      let pObj = cartObjArray.find((v) => v.pid === pid);
      // console.log(value);
      setTimeout(async () => {
        if (value <= "0") {
          alert("数量必须大于0");
          // numIpts[i].value = num;//当value小于等于0的时候，把当前商品的数量给到 当前的 商品数量输入框
          numIpts[i].value = 1;//小于等于0的时候等于1
        } else {
          // console.log(1);
          pObj.pnum = value;//把当前输入框的值给到请求参数pObj.pnum
          let { data } = await axios.get(cartUpdateAPI, {
            params: { pnum: value, pid, uid },
          });
          updateUl();//重新加载商品列表
          calCountPrice();
        }
      }, 500);//定时器每0.5秒执行一次
    };
  });

  //2-4给删除按钮添加事件
  lelBtns.forEach((btn, i) => {
    btn.onclick = async () => {
      let pid = btn.getAttribute("data-pid");//获取删除按钮上存的自定义属性值
      console.log(pid);
      //发送删除请求
      let { data } = await axios.get(cartDeleteAPI, { params: { pid, uid } });
      console.log(data);
      cartObjArray = cartObjArray.filter((v) => v.pid != pid);//利用filter方法把已经删除的商品在数组中去除，再加载商品列表的时候，该商品就会被删除
      updateUl();//重新加载商品列表
    };
  });

  //2-5单选按钮
  let singleSels = document.querySelectorAll(".single-sel");
  singleSels.forEach((sel, i) => {
    sel.onchange = () => {
      cartObjArray[i].checked = sel.checked;
      calCountPrice();
    };
  });

  //2-6全选按钮
  let allSelIpt = document.querySelector("#all-sel");
  allSelIpt.onchange = function () {
    console.log(this.checked);//true
    singleSels.forEach((v) => (v.checked = this.checked));
    cartObjArray.forEach((v) => (v.checked = this.checked));
    calCountPrice();
  };
}
// console.log(cartObjArray);//在函数外面是空，在函数里面就不是空的了？
//3-计算商品总价
function calCountPrice() {
  let singleSels = document.querySelectorAll(".single-sel");
  let count = 0;//记录总价
  console.log(cartObjArray);//在函数里能拿到商品列表数据
  cartObjArray.forEach((v,i) => {
    console.log(v.id);//id能拿到
    console.log(v.chacked);//chacked拿不到？是因为chacked是布尔值吗？
    if (v.checked) {//v.checked一直是true
      count += v.pprice * v.pnum;//总加等于商品价格乘以商品数量（每一个商品的总价累加到一起）
    }
  });
  console.log(count);//这是总价
  document.querySelector("#all-count-span").innerHTML = count;//给到显示总价的span
  let allSel = cartObjArray.every((v) => v.checked == true);//如果所有商品的checked属性都是true，那就让全选按钮的checked属性也变成true
  let allSelIpt = document.querySelector("#all-sel");
  allSelIpt.checked = allSel;
}
